package com.shop.cereshop.commons.tencent.moderation.service.impl;

import com.shop.cereshop.commons.tencent.moderation.config.TencentModerationConfig;
import com.shop.cereshop.commons.tencent.moderation.constant.ModerationConstant;
import com.shop.cereshop.commons.tencent.moderation.domain.request.CreateVideoModerationTaskParam;
import com.shop.cereshop.commons.tencent.moderation.domain.response.VideoModerationResult;
import com.shop.cereshop.commons.tencent.moderation.service.VideoModerationService;
import com.shop.cereshop.commons.tencent.moderation.task.VideoTaskManager;
import com.shop.cereshop.commons.tencent.moderation.util.ErrorMessageUtils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vm.v20210922.VmClient;
import com.tencentcloudapi.vm.v20210922.models.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @description:
 * @author zdd
 * @date 2025/10/26 23:55
 * @version 1.0
 */
@Slf4j
@Service
public class VideoModerationServiceImpl implements VideoModerationService {

    @Autowired
    private TencentModerationConfig config;

    @Autowired
    private VideoTaskManager videoTaskManager;

    @Override
    @Retryable(value = TencentCloudSDKException.class,
            maxAttempts = 3,
            backoff = @Backoff(delay = 1000, multiplier = 2))
    public VideoModerationResult createModerationTask(CreateVideoModerationTaskParam param) {
        long startTime = System.currentTimeMillis();

        try {
            VmClient client = createVmClient();
            CreateVideoModerationTaskRequest vmRequest = new CreateVideoModerationTaskRequest();
            // 任务类型：可选VIDEO（点播视频），LIVE_VIDEO（直播视频）
            String taskType = StringUtils.isNotBlank(param.getTaskType()) ? param.getTaskType() : "VIDEO";
            vmRequest.setType(taskType);
            vmRequest.setBizType(config.getModeration().getVideo().getBizType());
            // 设置任务优先级（可选）
            vmRequest.setPriority(param.getPriority() != null ? param.getPriority() : 0);
            // 设置回调（如果有）
            if (param.isEnabledCallback()) {
                vmRequest.setCallbackUrl(config.getModeration().getVideo().getCallbackUrl());
            }

            StorageInfo storageInfo = new StorageInfo();
            // URL-资源链接类型 COS-腾讯云对象存储类型
            String storageType = StringUtils.isNotBlank(param.getStorageType()) ? param.getStorageType() : "URL";
            storageInfo.setType(storageType);
            // 设置视频URL
            storageInfo.setUrl(param.getVideoUrl());

            TaskInput taskInput = new TaskInput();
            taskInput.setInput(storageInfo);
            // 设置数据ID
            String dataId = StringUtils.isNotBlank(param.getDataId()) ? param.getDataId() : UUID.randomUUID().toString();
            taskInput.setDataId(dataId);
            // 设置任务名称
            String taskName = StringUtils.isNotBlank(param.getTaskName()) ? param.getTaskName() : "CreateVideoModerationTask";
            taskInput.setName(taskName);
            vmRequest.setTasks(new TaskInput[]{taskInput});

            CreateVideoModerationTaskResponse response = client.CreateVideoModerationTask(vmRequest);
            // log.info("创建视频审核任务, request: {}, response: {}", JSON.toJSONString(vmRequest), JSON.toJSONString(response));

            if (response.getResults() != null && response.getResults().length > 0) {
                String taskId = response.getResults()[0].getTaskId();

                // 存储任务信息用于后续查询
                // videoTaskManager.addTask(taskId, param.getVideoUrl());

                log.info("视频审核任务创建成功, taskId: {}, videoUrl: {}, 耗时: {}ms",
                        taskId, param.getVideoUrl(), System.currentTimeMillis() - startTime);

                return VideoModerationResult.success(taskId, ModerationConstant.TASK_STATUS_PENDING)
                        .setCostTime(System.currentTimeMillis() - startTime);
            }

            return VideoModerationResult.fail("创建视频审核任务失败：返回结果为空");

        } catch (TencentCloudSDKException e) {
            log.error("创建视频审核任务失败, videoUrl: {}, error: {}, errorCode: {}", param.getVideoUrl(), e.getMessage(), e.getErrorCode(), e);
            String friendlyMessage = ErrorMessageUtils.getFriendlyErrorMessage(e);
            return VideoModerationResult.fail(friendlyMessage).setCostTime(System.currentTimeMillis() - startTime);
        }
    }

    @Override
    public VideoModerationResult getTaskResult(String taskId) {
        long startTime = System.currentTimeMillis();

        try {
            VmClient client = createVmClient();
            DescribeTaskDetailRequest request = new DescribeTaskDetailRequest();
            request.setTaskId(taskId);

            DescribeTaskDetailResponse response = client.DescribeTaskDetail(request);
            // log.info("获取视频审核任务详情, request: {}, response: {}", JSON.toJSONString(request), JSON.toJSONString(response));

            VideoModerationResult result = VideoModerationResult.success(taskId, response.getStatus())
                    .setCostTime(System.currentTimeMillis() - startTime);

            // 如果任务完成，设置审核结果
            if (ModerationConstant.TASK_STATUS_FINISH.equals(response.getStatus())) {
                result.setSuggestion(response.getSuggestion());
                result.setLabel(response.getLabel());
                // 根据Labels获取最高分作为score（如果有多个标签）
                if (response.getLabels() != null && response.getLabels().length > 0) {
                    long maxScore = 0;
                    for (TaskLabel label : response.getLabels()) {
                        if (label.getScore() != null && label.getScore() > maxScore) {
                            maxScore = label.getScore();
                        }
                    }
                    result.setScore(maxScore);
                }
            }

            log.info("查询视频审核任务结果, taskId: {}, status: {}, 耗时: {}ms",
                    taskId, response.getStatus(), result.getCostTime());

            return result;

        } catch (TencentCloudSDKException e) {
            log.error("查询视频审核任务结果失败, taskId: {}, error: {}", taskId, e.getMessage(), e);
            return VideoModerationResult.fail("查询视频审核任务结果异常: " + e.getMessage())
                    .setCostTime(System.currentTimeMillis() - startTime);
        }
    }

    @Override
    public boolean cancelTask(String taskId) {
        try {
            VmClient client = createVmClient();
            CancelTaskRequest request = new CancelTaskRequest();
            request.setTaskId(taskId);

            CancelTaskResponse response = client.CancelTask(request);
            log.info("取消视频审核任务, taskId: {}", taskId);
            // log.info("取消视频审核任务, request: {}, response: {}", JSON.toJSONString(request), JSON.toJSONString(response));

            return true;

        } catch (TencentCloudSDKException e) {
            log.error("取消视频审核任务失败, taskId: {}, error: {}", taskId, e.getMessage(), e);
            return false;
        }
    }

    private VmClient createVmClient() {
        Credential cred = new Credential(config.getSecretId(), config.getSecretKey());
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("vm.tencentcloudapi.com");
        httpProfile.setConnTimeout(config.getModeration().getVideo().getTimeout());

//        httpProfile.setReadTimeout(config.getModeration().getVideo().getTimeout());
//        httpProfile.setProtocol(HttpProfile.REQ_HTTPS);

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

//        clientProfile.setSignMethod(ClientProfile.SIGN_TC3_256);

        return new VmClient(cred, config.getRegion(), clientProfile);
    }

}
